import requests
import m3u8
import os
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
from concurrent.futures import ThreadPoolExecutor
import glob
import re
import json



# 下载m3u8文件
def download_m3u8(url,name):
    response = requests.get(url)
    with open(name, 'w') as file:
        file.write(response.text)

def AESDecrypt(cipher_text, key, iv):
    cipher_text = pad(data_to_pad=cipher_text, block_size=AES.block_size)
    aes = AES.new(key=key, mode=AES.MODE_CBC, iv=iv)
    cipher_text = aes.decrypt(cipher_text)
    # clear_text = unpad(padded_data=cipher_text, block_size=AES.block_size)
    return cipher_text

#get
def get_ts(url):
    try:
        response = requests.get(url, verify=False)
        response.raise_for_status()
        response.encoding = 'utf-8'
        return response.content
    except Exception as err:
        print(err)
        return b''

#保存ts文件
def save_ts(url, index):
    filename = os.path.join('./ts', str(index).zfill(5) + '.ts')
    with open(filename, 'wb') as f:
        ts = get_ts(url)
        f.write(ts)
    print(filename + ' is ok!')

def get_m3u8(url):
    headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36',
        'referer': url
    }
    res = requests.get(url,headers=headers)
    obj = re.compile(r'<div class="dplayer" data-config=.*?"video":{"url":"(?P<list>.*?)","pic"',re.S)
    result = obj.search(res.text)
    deskPicStr = result.group("list")
    return deskPicStr.replace("\\", "")


def delete_files_in_folder(folder_path):
    # 检查文件夹是否存在
    if not os.path.exists(folder_path) or not os.path.isdir(folder_path):
        print(f"The folder {folder_path} does not exist or is not a directory.")
        return

    # 列出文件夹中的所有文件
    files = os.listdir(folder_path)

    # 遍历文件列表，逐个删除文件
    for file in files:
        file_path = os.path.join(folder_path, file)
        try:
            if os.path.isfile(file_path):
                os.remove(file_path)
                print(f"Deleted file: {file_path}")
            else:
                print(f"Skipped non-file entry: {file_path}")
        except Exception as e:
            print(f"Failed to delete file {file_path}: {e}")

if __name__ == '__main__':
    delete_files_in_folder('./ts')
    # #先获取m3u8_url地址
    url = 'https://auto.zaqhvvi.com/archives/77421' #地址最后得/不要
    name = url.split('/')[-1]#m3u8文件
    names = name + ".m3u8"
    video_name = './video/'+name+'.mp4'

    m3u8_url = get_m3u8(url)
    download_m3u8(m3u8_url,names)
    playlist = m3u8.load(uri=names)#读取m3u8文件
    # #线程池，引入index可以防止合成时视频发生乱序
    with ThreadPoolExecutor(20) as pool:
        for index, seg in enumerate(playlist.segments):# enumerate 可以获取元素的索引和值
            pool.submit(save_ts, seg.uri, index)#参数1 函数 2，3函数参数

    key = get_ts(playlist.keys[-1].uri)#获取key
    files = glob.glob(os.path.join('./ts', '*.ts'))
    for file in files:
        with open(file, 'rb') as fr, open(video_name, 'ab') as fw:
            content = fr.read()
            encontent = AESDecrypt(content, key=key, iv=key)
            fw.write(encontent)
        print(file + ' is ok!')

